var pageIndex = 1, pageSize = 10;
var idle = 300;
var mode = '';
var currentData = [];

$(document).ready(function () {
  if (location.hash.match(/word=((\w|-|\.)+)/)) {
    location.hash = '';
    getData(RegExp.$1);
  } else {
    getData();
  }

  $('#inputSegment').keydown(debounce(idle, function () {
    pageIndex = 1;
    getData();
  }));

  $('[name="scales"]').on('change', function () {
    pageIndex = 1;
    getData();
  });

  $("#newWordBtn").click(function () {
    mode = 'add';
    $('#editTitle').html('添加词汇');
    $("#wordInfo").removeAttr('disabled');
    $('.form-group').removeClass('has-error');
    $('#wordInfo').val('');
    $('#outlineInfo').val('');
    $('#phoneticInfo').val('');
    $('#usPhoneticInfo').val('');
    $('#ukPhoneticInfo').val('');
    $('#scaleInfo').val(0);
    $('#explainsInfo').empty().append(generateInput(0,''));
    $("#editModal").modal();
  });

  $('#prevPage').click(function () {
    pageIndex--;
    getData(null, true, function (data) {
      if (data instanceof Array) {
        if (data.length > 0) {
          buildTable(data);
        } else {
          pageIndex++;
          toastMsg('已经是第一页', 'warning');
        }
      } else {
        pageIndex++;
        toastMsg('数据获取出错', 'error');
      }
    });
  });

  $('#nextPage').click(function () {
    pageIndex++;
    getData(null, true, function (data) {
      if (data instanceof Array) {
        if (data.length > 0) {
          buildTable(data);
        } else {
          pageIndex--;
          toastMsg('已经是最后一页', 'warning');
        }
      } else {
        pageIndex--;
        toastMsg('数据获取出错', 'error');
      }
    });
  });

  $(document).on('click', '.editable', function (e) {
    var index = +$(e.target).attr('data-index');
    if (currentData[index]) {
      initModalData(currentData[index]);
      mode = 'edit';
      $('#editModal').modal();
    } else {
      toastMsg('编辑数据出错', 'error');
    }
  });

  $('#saveChanges').click(function () {
    var postData = {
      word: $('#wordInfo').val().trim(),
      outline: $('#outlineInfo').val().trim(),
      phonetic: {
        default: $('#phoneticInfo').val().trim(),
        usPhonetic: $('#usPhoneticInfo').val().trim(),
        ukPhonetic: $('#ukPhoneticInfo').val().trim()
      },
      scale: +$('#scaleInfo').val()
    };
    if(!postData.word) {
      toastMsg('单词没有填写', 'error');
      return;
    }
    if (!postData.outline || !postData.phonetic.default) {
      toastMsg('释义或默认音标未正确填写', 'error');
      return;
    }

    var valid = true;
    var tempResult = [];
    var meaningArray = [];
    var propertyArray = [];
    $('input[data-seq]').each(function () {
      var data = $(this).val().trim();
      if (data.search(/^\w+\./) !== -1) {
        var handleResult = getMeaningsAndProperties(data);
        meaningArray.push(handleResult.meaning);
        propertyArray.push(handleResult.property);
        tempResult.push(data);
      } else {
        valid = false;
      }
    });

    if (!valid) {
      toastMsg('详细释义输入有误', 'error');
      return;
    } else {
      postData.explains = tempResult;
      postData.meanings = generateUniqueValues(meaningArray);
      postData.properties = generateUniqueValues(propertyArray);
    }

    var url = mode == 'add'? 'add': 'save';
    $.post('/'+ url, {data: JSON.stringify(postData)}, function (data) {
      if (data.errCode === 0) {
        toastMsg('保存成功', 'success');
        $('#editModal').modal('hide');
        getData();
      } else {
        toastMsg('保存失败. ' + data.errMsg, 'error');
      }
    });
  });
});

function getData(word, noBuildSign, callback) {
  var condition = {
    type: 'detail',
    pageIndex: pageIndex,
    pageSize: pageSize,
    scales: ' '
  };
  if (word) {
    condition.word = word;
    pageIndex = 1;
  }
  var segment = $('#inputSegment').val().trim();
  if (segment.length > 0) condition.segment = segment;
  var scales = '';
  $("[name='scales']:checked").each(function () {
    scales += ',' + $(this).val();
  });
  if (scales != '') {
    condition.scales = scales.slice(1);
  }

  $.post('/search', condition, function (data) {
    if (data.errCode === 0) {
      if (!(data.result instanceof Array)) {
        data.result = [data.result];
      }
      data.result.length > 0 && (currentData = data.result);
      !noBuildSign && buildTable(data.result);
      callback && callback(data.result);
    }
    else {
      toastMsg('数据获取出错', 'error');
      noBuildSign && callback && callback(null);
    }
  });
}

var scaleMapping = {
  1: '<span class="text-primary">小学</span>',
  2: '<span class="text-info">初中</span>',
  3: '<span class="text-success">高中</span>',
  0: '<span class="text-warning">未定义</span>'
};
var scaleMapping2 = {
  1: '小学',
  2: '初中',
  3: '高中',
  0: '未定义'
};

function buildTable(rows) {
  var html = '';
  $('[data-toggle="popover"]').popover('hide');
  for (var i = 0; i < rows.length; i++) {
    var obj = rows[i];
    html += '<tr><td class="text-primary">' + ((pageIndex - 1) * pageSize + i + 1) + '</td>';
    html += '<td>' + obj.word + '</td>';
    html += '<td class="text-info">' + loadPhonetic(obj.phonetic) + '</td>';
    html += '<td>' + loadExplain(obj.outline, obj.explains) + '</td>';
    html += '<td>' + obj.properties + '</td>';
    html += '<td>' + loadScale(obj.scale, i) + '</td>';
    html += '<td><a href="javascript:void(0)" class="material-icons editable" data-index="' + i + '" style="color:#22B699">assignment</a></td></tr>'
  }
  $('#tableData').empty().append(html);
  $('[data-toggle="popover"]').popover({
    html: true
  });

  $('body').off('click').on('click', function (e) {
    var target = $(e.target);
    var temp = target.attr('data-toggle');
    var isSelf = temp == 'popover' || target.hasClass('popover');
    if ($('[data-toggle="popover"]').has(target).length == 0 && $('.popover').has(target).length == 0 && !isSelf) {
      $('.popover').each(function () {
        var popId = $(this).attr('id');
        $('[aria-describedby="' + popId + '"]').click();
      });
    }
  });

}

function loadPhonetic(phonetic) {
  var html = '';
  if ((phonetic['usPhonetic'] || phonetic['ukPhonetic']) && phonetic.default) {
    var btnText = phonetic.default.length < 20 ? phonetic.default : phonetic.default.substring(0, 20) + '...';
    var phoneticTip = '';
    phoneticTip += '全球发音： ' + phonetic.default;
    phonetic['usPhonetic'] && (phoneticTip += '<br>美式发音： ' + phonetic['usPhonetic']);
    phonetic['ukPhonetic'] && (phoneticTip += '<br>英式发音： ' + phonetic['ukPhonetic']);
    html = '<button style="text-transform:none" type="button" class="btn btn-default little-padding no-margin" data-container="body" data-toggle="popover" ' +
      'data-placement="top" data-content="' + phoneticTip + '" title=""><span class="text-info">' + btnText + '</span></button>'
  } else {
    html = '<span class="text-info">' + (phonetic.default || '') + '</span>';
  }
  return html;
}

function loadExplain(outline, explains) {
  var html = '';
  if (explains.length > 0) {
    var explainStr = '';
    for (var i = 0; i < explains.length; i++) {
      explainStr += '<span>' + explains[i] + (i != explains.length - 1 ? '<br>' : '') + '</span>';
    }
    html = '<button type="button" class="btn btn-default little-padding no-margin" data-container="body" data-toggle="popover" ';
    html += 'data-placement="top" data-content=\'' + explainStr + '\' title=""><span class="text-success">' + (outline || '') + '</span></button>';
  } else {
    html = outline || '';
  }
  return html;
}

function loadScale(scale, index) {
  var text = scaleMapping[scale] || '';
  var html = '', radios = '';
  var id = randomString();

  for (var i = 0; i < 4; i++) {
    var isChecked = i == scale ? "checked='checked'" : "";
    radios += "<input onchange='editScale(this)' type='radio' id='" + (id + i) + "' value='" + i + "' name='" + id + "' " + isChecked + " />" +
      "<label style='color:#EEE' for='" + (id + i) + "'>&nbsp;" + scaleMapping2[i] + "&nbsp;</label>";
  }
  if (text) {
    html = '<button scale-index="' + index + '" id="pop' + id + '" style="text-transform:none" type="button" class="btn btn-default little-padding no-margin" data-container="body" data-toggle="popover" ' +
      'data-placement="top" data-content="' + radios + '" title=""><span class="text-info">' + text + '</span></button>'
  }
  return html;
}

function toastMsg(msg, type, timeout) {
  var color = '', DEFAULT_DELAY = 1500;
  switch (type || 'default') {
    case 'success':
      color = '#44ff44';
      break;
    case 'warning':
      color = '#f0ad4e';
      break;
    case 'error':
      color = '#ff7777';
      break;
    case 'info':
      color = '#337ab7';
      break;
    default:
      color = '#666666';
  }
  var time = typeof timeout === 'undefined' ? DEFAULT_DELAY : isNaN(+timeout) ? DEFAULT_DELAY : timeout;
  var content = '&nbsp;&nbsp;&nbsp;&nbsp;<span style=\'color:' + color + '\'>' + msg + '</span>';
  var html = '<button type="button" class="btn btn-default" style=\'display: none\' data-content="' +
    content + '" data-toggle=\'snackbar\' data-timeout=\'' + time + '\' id=\'snackBtn\'></button>';
  $('.toast-container').empty().append(html);
  $('#snackBtn').click();
}

function initModalData(word) {
  $('#editTitle').html('编辑词库');
  $('.form-group').removeClass('has-error');
  $('#wordInfo').attr('disabled', 'disabled');
  $('#wordInfo').val(word.word);
  $('#outlineInfo').val(word.outline);
  $('#phoneticInfo').val(word.phonetic.default);
  $('#usPhoneticInfo').val(word.phonetic.usPhonetic);
  $('#ukPhoneticInfo').val(word.phonetic.ukPhonetic);
  $('#scaleInfo').val(word.scale);

  var html = '';
  for (var i = 0; i < word.explains.length; i++) {
    var explain = word.explains[i];
    html += generateInput(i, explain);
  }
  $('#explainsInfo').empty().append(html);
}

function addExplain(btn) {
  var current = +$(btn).attr('data-seq');
  var allSiblings = $(btn).parent().siblings();
  changeSiblings(allSiblings, 1, current);
  $(btn).parent().next().after(generateInput(++current));
}

function removeExplain(btn) {
  var current = +$(btn).attr('data-seq');
  if (current === 0 && $('[data-seq]').length <= 3) {
    toastMsg('不能移除第一个', 'warning');
    return;
  }
  var allSiblings = $(btn).parent().siblings();
  $('[data-seq="' + current + '"]').each(function () {
    $(this).parent().remove();
  });
  changeSiblings(allSiblings, -1, current);
}

function changeSiblings($all, delta, bounds) {
  $all.each(function () {
    var inputs = $(this).children()[0];
    var inputSeq = +$(inputs).attr('data-seq');
    if (inputSeq > bounds) {
      $(inputs).attr('data-seq', inputSeq + delta);
    }
  });
}

function generateInput(i, explain) {
  return '<div class="form-group col-sm-9 no-margin">\
      <input required="required" style="width:100%" data-seq="' + i + '" placeholder="输入一个词性简称和释义,如：n. 例子" class="form-control col-sm-4" value="' + (explain || '') + '" />\
      </div>\
      <div class="form-group col-sm-1 btn-group no-margin">\
      <button onclick="addExplain(this)" style="padding:5px 5px" class="btn btn-primary form-control" data-seq="' + i + '">添加</button>\
      </div>\
      <div class="form-group col-sm-1 btn-group no-margin">\
      <button onclick="removeExplain(this)" style="padding:5px 5px" class="btn btn-warning form-control" data-seq="' + i + '">删除</button>\
      </div>';
}

function getMeaningsAndProperties(explain) {
  var start = explain.indexOf('.');
  return {
    property: explain.substring(0, start),
    meaning: explain.substring(start + 1, explain.length).trim()
  }
}

function generateUniqueValues(dataArray) {
  var tempArr = dataArray.join(',').split(/(,|;|，|；)/);
  var recorder = {};
  var result = '';
  for (var i = 0; i < tempArr.length; i++) {
    if (tempArr[i].search(/(,|;|，|；)/) === -1 && tempArr[i].trim() !== '')
      recorder[tempArr[i].trim()] = true;
  }
  for (var j in recorder) {
    result += ',' + j.trim();
  }
  return result === '' ? result : result.substring(1);
}

function editScale(element) {
  var button = $("#pop" + $(element).attr('name'));
  var index = +button.attr('scale-index');
  currentData[index].scale = +$(element).val();
  $.post('/save', {data: JSON.stringify(currentData[index])}, function (data) {
    if (data.errCode === 0) {
      toastMsg('保存成功', 'success');
      $('#editModal').modal('hide');
      getData();
    } else {
      toastMsg('保存失败. ' + data.errMsg, 'error');
    }
  });
  setTimeout(function () {
    button.click();
  }, 200);
}

function randomString(len) {
  len = len || 32;
  var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
  var maxPos = $chars.length;
  var pwd = '';
  for (var i = 0; i < len; i++) {
    pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
  }
  return pwd;
}

//todo list
/**
 * 1. 异步json获取, tableData生成 √
 * 2. 重构查询接口, 通过内存map查询 √
 * 4. 全文本超纲词检测, 单个接口测试 √
 * 5. merge已有的scale √
 * 6. sqlite模式数据适配 √
 * 7. 分页 √
 * --------------------------
 * 3. 查询demo页面事件， 分页事件响应 √
 * 4. 保存接口，mongo+sqlite同步 √
 * 5. 页面UI优化，hover范围增加编辑图标 √
 * 6. 编辑事件相应 √
 * 7. 快速编辑范围 √
 * ---------------------------
 * 1. API文档页面修改，增加全文检索实例 !-
 * 2. API文档页面代码高亮插件google-code-prettify √
 * 3. C#接口和demo，以及API文档 √
 * 4. docker部署 √
 * 5. 创建单词接口 -
 * */